<script setup lang="ts">
import { getAnnouncementByIdApi, getAnnouncementLinkApi, getAnnouncementOSSApi } from '@/api/innovationSquare/competitionApi'
import { onMounted, ref } from 'vue';
import type { Competition } from '../../home/types/Competition'
import { useRoute } from 'vue-router';
import mammoth from 'mammoth';
import { Breadcrumb, BreadcrumbItem, Button, Layout } from 'ant-design-vue';
import router from '@/router'

const route = useRoute()
const competitionId = String(route.params.competitionId);

const competitionUrl = ref<string>('');
const competitionLink = ref<string>('');
const activeKey = ref('1');
const loading = ref(false);
const ossContent = ref<string>('');
const competition = ref<Competition>({
  competitionId: Number(competitionId.valueOf),
  name: '',
  description: '',
  tags: [],
  likeNum: 0,
  shareNum: 0,
  lookNum: 0,
  publisherTime: '',
  status: '',
  likeTrue: false,
  text: '',
});
// 模拟获取 OSS 内容的函数
const fetchDocumentContent = async (url: string) => {
  try {
    // console.log("Fetching document content from URL:", url);
    const response = await fetch(url);
    // console.log("Fetch response received:", response);

    if (!response.ok)
      throw new Error(`HTTP error! status: ${response.status}`);

    const arrayBuffer = await response.arrayBuffer();
    // console.log("ArrayBuffer received:", arrayBuffer);

    const { value: html } = await mammoth.convertToHtml({ arrayBuffer });
    // console.log("Extracted HTML:", html);

    ossContent.value = html; // 替换为实际获取的内容
  }
  catch (err) {
    console.error('Error extracting document content:', err);
  }
};

const fetchCompetition = async () => {
  loading.value = true;

  if (!competitionId) {
    console.error('No projectId found:', competitionId);
    return;
  }
  try {
    const detailsResponse = await getAnnouncementByIdApi(competitionId)
    competition.value = detailsResponse.data;

    const oss = await getAnnouncementOSSApi(competitionId)
    competitionUrl.value = oss.data;

    fetchDocumentContent(competitionUrl.value);
    const link = await getAnnouncementLinkApi(competitionId)
    competitionLink.value = link.data;
  }
  catch (error) {
    console.error('Error fetching competition data:', error);
  }
  finally {
    loading.value = false
  }
}

fetchCompetition();

onMounted(() => {
  fetchCompetition();
});

const titleParts = '双创广场>赛事信息>详情'.split('>');
const handleBreadcrumbClick = (part: string) => {
  if (part === '赛事信息' || part === '双创广场')
    router.push('/user/dachuang/saishi');
}
</script>

<template>
  <div class="data-market">
    <div class="top-menu">
      <Breadcrumb separator=">" :style="{ fontSize: '1.5rem', fontWeight: 'bold' } " style="margin-left: 1rem; margin-right: 1rem;">
        <BreadcrumbItem
          v-for="(part, index) in titleParts.slice(0, -1)"
          :key="index"
          style="color: #A0A0A0; cursor: pointer;"
          @click="handleBreadcrumbClick(part)"
        >
          {{ part }}
        </BreadcrumbItem>
        <BreadcrumbItem>{{ titleParts[titleParts.length - 1] }}</BreadcrumbItem>
      </Breadcrumb>
    </div>

    <div class="navtop" style="margin:1rem; margin-top: 0.5rem;">
      <span style="font-size: 1.5rem; padding: 1rem; font-weight: bold;">
        {{ competition ? competition.name : '项目详情' }}
      </span>

      <div style="padding-left: 1rem; padding-right: 1rem; font-size: 1rem; font-weight: bold; color: #A0A0A0; margin-bottom: 1rem;">
        发布时间: {{ competition ? competition.publisherTime : '未发布' }}
      </div>

      <div class="tags-container" style="margin-left: 1rem; margin-right: 1rem;">
        <a-tag v-for="(tag, index) in competition.tags" :key="index" style="margin-right: 0.5rem; margin-bottom: 0.5rem; font-size: 1rem;">
          {{ tag }}
        </a-tag>

        <a :href="competitionLink" target="_blank" rel="noopener noreferrer" style="font-size: 1rem;">
          <Button type="primary">查看原文</Button>
        </a>
      </div>
    </div>

    <div style="margin-left: 1rem; margin-right: 1rem;">
      <Layout>
        <div style="overflow-y: hidden; overflow-x: hidden;">
          <a-card class="project-card">
            <a-tabs v-model="activeKey" :tab-bar-style="{ textAlign: 'center' }">
              <a-tab-pane key="1" tab="赛事详情">
                <div class="card-wrapper">
                  <div class="content-container">
                    <div v-html="ossContent || '文档内容无法显示'" />
                  </div>
                </div>
              </a-tab-pane>

              <a-tab-pane key="2" tab="招募信息">
                <div class="content-container">
                  <div :key="competition.competitionId" class="cardWrapper">
                    <div style="margin-bottom: 2em; overflow-y:auto;">
                      <span class="tabTitle">{{ competition.name }}</span>
                      <p style="margin-top: 10px;">
                        {{ competition.description }}
                      </p>
                    </div>
                    <div style="margin-bottom: 2em; overflow-y:auto;">
                      <span class="tabTitle">赛道介绍</span>
                      <p style="margin-top: 10px;">
                        {{ competition.text }}
                      </p>
                    </div>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-card>
        </div>
      </Layout>
    </div>
  </div>
</template>

<style scoped lang="scss">
.data-market {
  overflow: hidden;

  .top-menu {
    align-items: center;
    justify-content: space-between;
    max-height: 6 rem;
  }

  .navtop {
    display: flex;
    flex-direction: column;
    background-color: rgb(255, 255, 255);
    border-radius: 0.5rem;
    .tags-container {
      display: flex;
      align-items: center; // 垂直居中对齐
      margin-bottom: 0.4em;
      flex-wrap: wrap;

      .tags {
        display: inline-block;
        font-size: 1rem;
        background-color: #F2F2F4;
        color: rgb(42, 41, 41);
        padding: 0.5rem;
        border-radius: 0.5rem;

      .link-button {
        margin-left: auto; // 自动左边距，使其靠右
      }
    }
  }
}
}

.project-card {
    .project-image {
      max-width: 100%;
      height: auto;
    }

    .tabs {
      .tabTitle {
        font-size: 3rem;
        font-weight: 800;
        margin-bottom: 1em;
        display: inline-block;

      }
      .card-wrapper {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
  }
  .content-container {
  max-height: 50vh;
  overflow-y: auto; // 启用垂直滚动
}

}
</style>
